﻿using System.IO;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using K9Nano.Dependency;

namespace K9Nano.Storage
{
    public interface IFileStorage
    {
        bool Exists([NotNull] string path) => File.Exists(path);

        ValueTask<bool> ExistsAsync([NotNull] string path, CancellationToken cancellation) => new ValueTask<bool>(File.Exists(path));

        Stream OpenRead([NotNull] string path) => File.Open(path, FileMode.Open, FileAccess.Read);

        ValueTask<Stream> OpenReadAsync([NotNull] string path, CancellationToken cancellation)
            => new ValueTask<Stream>(File.Open(path, FileMode.Open, FileAccess.Read));

        Stream OpenWrite([NotNull] string path) => File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

        ValueTask<Stream> OpenWriteAsync([NotNull] string path, CancellationToken cancellation)
            => new ValueTask<Stream>(File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite));

        void Delete([NotNull] string path) => File.Delete(path);

        ValueTask DeleteAsync([NotNull] string path, CancellationToken cancellation)
        {
            File.Delete(path);
            return new ValueTask();
        }

        long GetLength([NotNull] string path) => new FileInfo(path).Length;

        ValueTask<long> GetLengthAsync([NotNull] string path, CancellationToken cancellation) => new ValueTask<long>(new FileInfo(path).Length);

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="ext">扩展名，如：.jpg</param>
        /// <returns>文件的访问路径</returns>
        string Save(Stream stream, string ext);

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="ext">扩展名，如：.jpg</param>
        /// <returns>文件的访问路径</returns>
        ValueTask<string> SaveAsync(Stream stream, string ext, CancellationToken cancellation);


        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>文件的访问路径</returns>
        string Save(string path) => Save(File.OpenRead(path), new FileInfo(path).Extension);

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>文件的访问路径</returns>
        /// <returns>文件的访问路径</returns>
        ValueTask<string> SaveAsync(string path, CancellationToken cancellation) => SaveAsync(File.OpenRead(path), new FileInfo(path).Extension, cancellation);

    }
}